/* Construction specific application form settings */

$(document).ready(function() {
	/* 
	 * Setup the accordion
	 */
	$("#accordion").accordion({
		collapsible: false,
		active: 0,
		//event: "none"
		autoHeight: false
	});
	// Hack per disabilitare lo slot bottom al click del mouse
	var accordion = $( "#accordion" ).data("accordion");
	accordion._std_clickHandler = accordion._clickHandler;
	accordion._clickHandler = function( event, target ) {
		var clicked = $( event.currentTarget );
		if (! clicked.hasClass("slot_bottom"))
			this._std_clickHandler(event, target);
	};

	/* 
	 * Setup dataTables
	 */	
	var cTable = $('#lista').dataTable({
		"oLanguage"			: {"sUrl": "/js/dataTables/jquery.dataTables.it_IT.txt"},
		"bJQueryUI"			: true,
		"sDom"				:'<"H"lfr>t<"F"ip>', // 'frtip'
		"iDisplayLength"	: 10,
		"sPaginationType"	: "full_numbers",
		"bStateSave"		: true,
		"bAutoWidth"		: false,
		"aoColumns"			: [
			{ "mDataProp": "id", "sWidth": "50px" }, 
			{ "mDataProp": "name" }, 
			{ "mDataProp": null, "sWidth": "60px" } 
		],
	});	
	
	// binds form submission and fields to the validation engine
	$("#detail").validationEngine();
	$("detail").submit(function(e) {
		e.preventDefault();
	});
	
	/* 
	 * Setup the "Add material" button
	 */
	$("#material_add").click( 
		function() { 
			ajaxAddMaterial();
		}
	);

	// Dialog material list
	$( ".newmat" ).live("click", function() {
		$("#dialog_material_list > option").remove();
		$("#dialog_category_list > option").remove();
		
		$("#name_field").attr("value", $(this).attr("id"));
		$("#id_field").attr("value", $(this).attr("id").replace('_name','_id'));

		$.getJSON("/ajax/get-material-categories-list/format/json", false, function(data){
			$("#dialog_category_list").append(
					$("<option></option>").val(0).html("Tutte le categorie")
			);
			$.each(data, function(k, cat){
				$("#dialog_category_list").append(
					$("<option></option>").val(cat.id).html(cat.name)
				);
			});
		});

		$.getJSON("/ajax/get-material-list/format/json", false, function(data){
			$.each(data, function(k, mat){
				$("#dialog_material_list").append(
					$("<option></option>").val(mat.id).html(mat.name)
				);
			});
		});
		$( "#dialog-form" ).dialog( "open" );
	});

	$("#dialog_category_list").change(function () {
		$("#dialog_material_list > option").remove();
		$.getJSON("/ajax/get-material-list/format/json/id/" + $("#dialog_category_list").val(), false, function(data){
			$.each(data, function(k, mat){
				$("#dialog_material_list").append(
					$("<option></option>").val(mat.id).html(mat.name)
				);
			});
		});
	});
	

	/*
	 * Dialog selezione categoria
	 */
	$('#X-browse-categories').dialog({
		width: 300,
		height: 200,
		modal: true,
		resizable: false,
		draggable: false,
		autoOpen: false,
		beforeClose: function () { doUpdateConstructionCategory(); },
		buttons: {
			Ok: function() { $(this).dialog('close'); }
		}
	});
	// Trigger click campo categoria
	$('#construction_category').click(function(ev) {
		$('#X-browse-categories').dialog('open');
		$('#construction_categories').attr('value', $('#construction_category_id').val());
	});

}); // end of document.ready()

/*
 * Activates the construction details accordion panel
 */
function openConstructionDetails(id) {
	$("#panel-top").empty();
	$("#panel-mats").empty();
	$("#panel-bottom").empty();
	$("#accordion").accordion('activate',1);
	getConstructionDetailsById(id);
}

/*
 * Aggiorna la categoria della costruzione
 */

function doUpdateConstructionCategory() {
	var cat = $('#construction_categories :selected');
	$('#construction_category').attr('value', cat.text());
	$('#construction_category_id').attr('value', cat.val());
}

/*
 * Ajax call for construction details
 */
function getConstructionDetailsById(id) {
	waitingDialog({title: "Caricamento", message: "Interrogazione database<br>in corso..."});
	// Pulizia form, step 1: valore campi form
	$("#detail").find(':input').each(function() {
		switch(this.type) {
			case 'password':
			case 'select-multiple':
			case 'select-one':
			case 'text':
			case 'textarea':
				$(this).val('');
				break;
			case 'checkbox':
			case 'radio':
				this.checked = false;
		}
	});
	// Pulizia form, step 2: campi dinamici (materiali)
	$(".dyn").remove();
	$("#material_order").attr("value", 10);

	$.getJSON("/ajax/get-construction-details-by-id", { 'id' : id, 'format' : 'json' }, function(data){
		$('#construction_name').attr('value', data[0]['name']);
		$('#construction_source').attr('value', data[0]['source']);
		$('#construction_category_id').attr('value', data[0]['id_category'] ?  data[0]['id_category'] : 0);
		$('#construction_category').attr('value', data['category'] ?  data['category'] : "Non categorizzato");
		$('#construction_layers').attr('value', data['layers']);
		$('#construction_hci').attr('value', data['props']['physical'][0]['hci']);
		$('#construction_rad_i').attr('value', data['props']['physical'][0]['rad_i']);
		$('#construction_sri').attr('value', data['props']['physical'][0]['sri']);
		$('#construction_hco').attr('value', data['props']['physical'][0]['hco']);
		$('#construction_rad_o').attr('value', data['props']['physical'][0]['rad_o']);
		$('#construction_sro').attr('value', data['props']['physical'][0]['sro']);
		$('#construction_uvalue_sts').attr('value', data['props']['thermal'][0]['uvalue_sts']);
		$('#construction_rvalue').attr('value', data['props']['thermal'][0]['rvalue']);
		$('#construction_uvalue').attr('value', data['props']['thermal'][0]['uvalue']);
		$('#construction_url').attr('value', data['props']['thermal'][0]['url']);
		$('#construction_lrl').attr('value', data['props']['thermal'][0]['lrl']);
		$('#construction_bs_uvalue_sts').attr('value', data['props']['thermal'][0]['bs_uvalue_sts']);
		$('#construction_bs_rvalue').attr('value', data['props']['thermal'][0]['bs_rvalue']);
		$('#construction_bs_uvalue').attr('value', data['props']['thermal'][0]['bs_uvalue']);
		//var id;
		//var end_id = start_id + data['layers'];
		for (var layer in data['materials']) {
			id_mat = $("#material_order").attr("value");
			ajaxAddMaterial();
			$('#new_material_' + id_mat + '_name').attr('value', data['materials'][layer]['name']);
			$('#new_material_' + id_mat + '_thickness').attr('value', data['materials'][layer]['thickness']);
			$('#new_material_' + id_mat + '_id').attr('value', data['materials'][layer]['id']);

		}
		closeWaitingDialog();
		
		$("#construction_prev").unbind('click');
		$("#construction_prev").bind('click', function(e) {
			e.preventDefault();
			getConstructionDetailsById(data["prev"]);
		});
		
		$("#construction_next").unbind('click');
		$("#construction_next").bind('click', function(e) {
			e.preventDefault();
			getConstructionDetailsById(data["next"]);
		});
		
		// Azione: elimina costruzione
		$("#construction_del").unbind('click');
		$("#construction_del").bind('click', function(e) {
			e.preventDefault();
			answer = confirm("Confermi l'eliminazione di questa costruzione?");
			if (answer) {
				$.ajax( {
					type: "GET",
					url: "/ajax/delete-construction",
					data: { "id" : id, "format" : "json" },
					success: function() {
						getConstructionDetailsById(data["next"]);
					}
				});	
			}
		});
		
		// Azione: aggiungi (nuova) costruzione
		$("#construction_add").unbind('click');
		$("#construction_add").bind('click', function(e) {
			e.preventDefault();
			// Pulizia form, step 1: valore campi form
			$("#detail").find(':input').each(function() {
				switch(this.type) {
					case 'password':
					case 'select-multiple':
					case 'select-one':
					case 'text':
					case 'textarea':
						$(this).val('');
						break;
					case 'checkbox':
					case 'radio':
						this.checked = false;
				}
			});
			// Pulizia form, step 2: campi dinamici (materiali)
			$(".dyn").remove();
			$("#material_order").attr("value", 10);

			// Importante
			id = "0";
		});
		
		// Azione: salva costruzione
		$("#construction_save").unbind('click');
		$("#construction_save").bind('click', function(e) {
			e.preventDefault();	
				
			if (id == 0) {
				console.log("Saving a new construction");
			} else {
				console.log("Updating an existing construction");
			}

			$.ajax( {
				type    : "POST",
				url     : "/preprocessor/costruzioni?function=SaveConstruction&format=json&id=" + id,
				data    : $("#detail").serialize(),
				success : function(response) {
					$("#detail").validationEngine("hideAll");
					if (response.esito > 0) {
						$("#construction_name").validationEngine('showPrompt', response.messages, 'pass', 'topRight', true);
						// Aggiorniamo l'id dell'elemento visualizzato (importante in case di inserimento di un nuovo elemento)
						id = response.id;
					}
					if (response.esito < 0) {
						$.each(response.messages, function(field, errorObj) {
							$.each(errorObj, function (errorType, errorMsg) {
								$("#" + field).validationEngine('showPrompt', errorMsg, 'error', 'topRight', true);
							});
						});
					}
					if (response.esito == 0){
						$("#construction_name").validationEngine('showPrompt', response.messages, 'error', 'topRight', true);
					}
				}
			});
		});
		
	});
} 

// Retrieve new element's html from controller
function ajaxAddMaterial() {
	var id = $("#material_order").attr('value');
	$.ajax({
		type: "GET",
		url: "/preprocessor/costruzioni",
		data: { "function" : "add-construction-material", "material_order" : id }, 
		async: false,
		success: function(newElement) {
			// Insert new element before the Add button
			$("#construction_hci-label").before(newElement);
			// Increment and store id
			$("#material_order").attr('value', ++id);
		}
	});
}

////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////Script per modal window//////////////////////////////////

	$(function() {
		// a workaround for a flaw in the demo system (http://dev.jqueryui.com/ticket/4375), ignore!
		$( "#dialog:ui-dialog" ).dialog( "destroy" );
		
		var categoria = $( "#categoria" ),
			materiale = $( "#materiale" ),
			allFields = $( [] ).add( categoria ).add( materiale ),
			tips = $( ".validateTips" );

		$( "#dialog-form" ).dialog({
			autoOpen: false,
			height: 300,
			width: 350,
			modal: true,
			buttons: {
				"Ok!": function() {
					//alert ('id = ' + $('#dialog_material_list').val());
					//alert ('nome mat = ' + $('#dialog_material_list :selected').html());
					//alert ("id campo form per il nome: " + $("#name_field").val());
					//alert ("id campo form per hidden: " + $("#id_field").val());
					$("#" + $("#name_field").val()).attr("value", $('#dialog_material_list :selected').html());
					$("#" + $("#id_field").val()).attr("value", $('#dialog_material_list').val());
					$( this ).dialog( "close" );
				},
				Cancel: function() {
					$( this ).dialog( "close" );
				}
			},
			close: function() {
				allFields.val( "" ).removeClass( "ui-state-error" );
			}
		});
	});
